//
//  DataHandel.m
//  Days
//
//  Created by lanou3g on 16/1/6.
//  Copyright © 2016年 dss. All rights reserved.
//

#import "DataHandel.h"
#import <CoreLocation/CoreLocation.h>
#import "Model.h"

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonHMAC.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netdb.h>
#import <arpa/inet.h>
@interface DataHandel ()<CLLocationManagerDelegate>

@property(nonatomic,strong)CLLocationManager *locationManager;

@end


static DataHandel *_dataHandel = nil;
@implementation DataHandel
+(instancetype)sharedHandel{
    return [[self alloc]init];
    
}

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_dataHandel == nil) {
            _dataHandel  =[super allocWithZone:zone];
        }
    });
    return _dataHandel;
}

//根据网址得到天气数据的方法
-(void)getDataWithURL:(NSString *)url withBlock:(GETBLOCK) block{
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *datatask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
        id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //判断是否有数据
        if (object == nil || [object valueForKey:@"result"] == nil) {
            
            //发送通知 
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"city" object:nil];
            
        }else{
            //如果请求的数据不为空才把值传出去
            dispatch_async(dispatch_get_main_queue(), ^{
                block(object);
                
            });
        }
        
        
        
    }];
    
    
    //执行任务
    [datatask resume];
    
    
}

- (void)getData:(NSString *)url withBlock:(GETBLOCK)block{
  
    [self getDataWithURL:url withBlock:^(id object) {
       
       
        NSDictionary *dict = object[@"result"];
        NSDictionary *dic1 = dict[@"data"];
        
     //   if ([dic1 isEqual:@"holiday"]) {
            
        self.str = dic1[@"holiday"];
            
     //   }else{
        
      //  self.str = dic1[@"holidaylist"];
            
    //    }
     
        NSData *jsonData = [self.str dataUsingEncoding:NSUTF8StringEncoding];
        
        NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        
        NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:10];
        
        
        for (NSDictionary *dic in array) {
            
           
           Model *model = [[Model alloc] init];
           [model setValuesForKeysWithDictionary:dic];
           [array1 addObject:model];
                       
        }
        
        self.dataArray = [NSArray arrayWithArray:array1];
            block(self.dataArray);

        
       
    }];
    
       dispatch_async(dispatch_get_main_queue(), ^{
           
          
       });
    
}



//开始定位
-(void)startLocation{
    if (self.locationManager == nil) {
        self.locationManager =[[ CLLocationManager alloc]init];
    
    }
    //设置代理
    self.locationManager.delegate  = self;
    //请求用户允许使用定位
    [self.locationManager requestWhenInUseAuthorization];
    //定位精度
    CLLocationDistance distance = 100;
    self.locationManager.distanceFilter = distance;
    
    //定位质量
    
    self.locationManager.desiredAccuracy =kCLLocationAccuracyThreeKilometers;
    
    
    //判断定位服务是否可用 并且用户是否允许定位
    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied ) {
        
    }
    
    //iOS7 以前
    //开启定位服务,开始更新位置
    [self.locationManager startUpdatingLocation];

    
}
#pragma mark -- 逆地理编码(根据经纬度获取地址)
-(void)getAddressWithCoordinate:(CLLocationCoordinate2D )coordinate withFinish:(unGeographyCodingBlock)finishBlock{
    
    //编码类
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    //根据CLLocationCoordinate2D 构造一个 CLLocation
    CLLocation *location = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //拿出第一个元素
            CLPlacemark *mark = placemarks.firstObject;
            finishBlock(mark.name);
         
        
        });
        
        
    }];

}

#pragma mark -- 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    
    
}

#pragma mark -- 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = locations.firstObject;
    
    CLLocationCoordinate2D coordinate = location.coordinate;
    
    if (self.updateBlock) {
        self.updateBlock(coordinate);
    }
}


#pragma mark -- 去掉空格和换行符
-(NSString *)removeBlankSpaceWithStr:(NSString *)string{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    string= [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    return string;
    
}



#pragma mark -- 判断网络
-(BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
    
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}

#pragma mark -- 读出来
-(void)readWithStr:(NSString *)string byreader:(NSString *)reader andDelegate:(NSObject *)delegate{
    // 创建合成对象，为单例模式
    _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    _iFlySpeechSynthesizer.delegate = delegate;
    //设置语音合成的参数
    //语速,取值范围 0~100
    [_iFlySpeechSynthesizer setParameter:@"50" forKey:[IFlySpeechConstant SPEED]];
    //音量;取值范围 0~100
    [_iFlySpeechSynthesizer setParameter:@"50" forKey: [IFlySpeechConstant VOLUME]];
    //发音人,默认为”xiaoyan”;可以设置的参数列表可参考个 性化发音人列表
    //xiaoyan xiaoyu xiaoqi xiaofeng xiaoxin xiaokun
    [_iFlySpeechSynthesizer setParameter:reader forKey: [IFlySpeechConstant VOICE_NAME]];
    //音频采样率,目前支持的采样率有 16000 和 8000
    [_iFlySpeechSynthesizer setParameter:@"8000" forKey: [IFlySpeechConstant SAMPLE_RATE]];
    //asr_audio_path保存录音文件路径，如不再需要，设置value为nil表示取消，默认目录是documents
    [_iFlySpeechSynthesizer setParameter:nil forKey: [IFlySpeechConstant TTS_AUDIO_PATH]];
    //启动合成会话
    [_iFlySpeechSynthesizer startSpeaking: string];
}



@end
